#!/bin/sh

URL="https://github.com/fatedier/frp/releases/download/v0.63.0/frp_0.63.0_linux_amd64.tar.gz"
FILENAME=$(basename "$URL")
DIRNAME="${FILENAME%.tar.gz}"

echo "开始下载 frp: $URL"
if ! curl -fLO "$URL"; then
    echo "下载失败，请检查网络连接或URL是否正确"
    exit 1
fi

echo "开始解压 $FILENAME..."
if ! tar -xzf "$FILENAME"; then
    echo "解压失败"
    exit 1
fi

echo "删除压缩包 $FILENAME"
rm -f "$FILENAME"
if [ ! -d "$DIRNAME" ]; then
    echo "目录 $DIRNAME 不存在，解压可能出现问题"
    exit 1
fi

echo "删除目录中的指定文件"
cd "$DIRNAME" || exit 1
rm -f frps frps.toml LICENSE

######################## 配置 frpc ########################

SERVICE_URL="https://gitee.com/shared-knowledge/frp/raw/master/frpc/frpc.service"
DEST_PATH="/etc/systemd/system/frpc.service"

echo "开始下载 frpc.service: $SERVICE_URL"
if ! curl -fL "$SERVICE_URL" -o /tmp/frpc.service; then
    echo "下载失败，请检查网络连接或URL是否正确"
    exit 1
fi
if [ ! -f "/tmp/frpc.service" ]; then
    echo "文件下载失败，临时文件不存在"
    exit 1
fi

echo "将文件部署到 $DEST_PATH"
if ! sudo mv /tmp/frpc.service "$DEST_PATH"; then
    echo "部署失败，请确保拥有root权限"
    exit 1
fi
sudo chmod 644 "$DEST_PATH"

echo "重新加载systemd配置"
if ! sudo systemctl daemon-reload; then
    echo "systemd配置重载失败"
    exit 1
fi


CONFIG_URL="https://gitee.com/shared-knowledge/frp/raw/master/frpc/frpc.toml"

echo "开始下载 frpc.toml: $CONFIG_URL"
if ! curl -fL "$CONFIG_URL" -o "frpc.toml"; then
    echo "配置文件下载失败，请检查网络连接或URL是否正确"
    exit 1
fi
if [ ! -f "frpc.toml" ]; then
    echo "错误：配置文件未成功保存到 $DIRNAME 目录"
    exit 1
fi

######################## 启动 frpc ########################

systemctl enable frpc
systemctl start frpc
